<template>
  <!-- 重新设计任务信息页面逻辑 -->
  <view class="info_box">
    <action-bar :options="navOptions"></action-bar>

    <view class="card">
      <uni-section :title="item.name" :padding="item.padding" type="line" v-for="(item, index) in formList"
        :key="index">
        <template v-for="(list, indexs) in item.children">
          <view :class="list.class" :key="indexs" v-if="list.type == 'span'">
            <view class="label required">{{ list.name }}</view>
            <span class="content">{{ valiFormData[list.value] }}</span>
          </view>
          <map class="map" v-else-if="list.type == 'map'" :latitude="centerPoint.latitude"
            :longitude="centerPoint.longitude" :circles="circles" :scale="scale" :markers="markers" />
          <view :class="list.class" v-else-if="list.type == 'textarea'">
            <textarea class="content" v-model="valiFormData.remark" placeholder="暂无备注信息" disabled />
          </view>
        </template>
      </uni-section>
    </view>

    <view style="height: 100rpx"> </view>

    <view class="info_box-btn">
      <!-- 是执业人员但不是项目负责人 -->
      <view class="info_box-btn-combination" v-if="isPractice == '1' && isProjectHead == '0'">
        <view class="info_box-btn-combination-btn" @click="sureTo">
          {{ practiceState == "look" ? "查看执业" : "开始执业" }}
        </view>
        <view class="info_box-btn-combination-btn" v-if="showLook('write2')" @click="navToLook">
          查看执业
        </view>
      </view>

      <view class="info_box-btn-sure" v-else-if="
        isPractice == '0' &&
        isProjectHead == '1' &&
        isConfirm == '0' &&
        practiceStates
      " @click="navTo">
        确认任务
      </view>

      <view class="info_box-btn-combination" v-else-if="isPractice == '1' && isProjectHead == '1'">
        <view class="info_box-btn-combination-btn sureBtns" @click="navTo" v-if="isConfirm == '0' && practiceStates">
          确认任务</view>
        <view class="info_box-btn-combination-btn" @click="sureTo">{{ practiceState == "look" ? "查看执业" : "开始执业" }}
        </view>
      </view>
      <!-- 当该项目的执业人员不是本账户所属或者该项目的项目负责人不是本账户所属，并且practiceState为look时，展示查看执业按钮；此步骤为服务机构或者其他角色从报告中查看项目详情时 -->
      <view class="info_box-btn-combination" v-else-if="
        (isPractice != '1' || isProjectHead != '1') && practiceState == 'look'
      ">
        <view class="info_box-btn-combination-btn" @click="sureTo">查看执业
        </view>
      </view>
    </view>

    <drag-button :isDock="true" :existTabBar="true" :title="title" @btnClick="btnClick" />
    <toast></toast>
  </view>
</template>

<script>
import QQMapWX from "@/static/qqmap-wx-jssdk.js";
import dragButton from "@/components/drag-button/drag-button.vue";
import { mapState, mapMutations } from "vuex";
import { baseApiUrl } from "@/config.js";
export default {
  omponents: {
    dragButton,
  },
  computed: {
    ...mapState({
      practiceState: (state) => state.manage.practiceState,
      form: state => state.unitTask.form
    }),
  },
  data() {
    return {
      baseApiUrl: baseApiUrl,
      title: "离线上报",
      // 页面导航栏的固定写法
      navOptions: {
        statusBar: "dark",
        left: {
          icon: "back",
        },
        center: {
          title: "任务信息",
        },
      },

      // 表单数据
      valiFormData: {
        projectName: null,
        projectAddress: null,
        name: null,
        startDate: null,
        endDate: null,
        remark: null,
      },

      /**
       * map组件内的数据项
       * key: 高德地图的key
       * centerPoint: 经纬度信息
       * circles: 圆的字段
       * scale: 地图缩放程度
       * markers: 点坐标
       */
      key: "DKCBZ-AX5LV-RVSPF-UA735-DABVO-YLFNJ",
      centerPoint: {
        latitude: null, // 纬度，一般小的
        longitude: null, // 经度， 一般大的
      },
      circles: [],
      scale: null,
      markers: [],

      // 当数据请求中或请求失败时，操作人不可点击确认执业操作按钮
      displayBox: false,

      //! 通过上个页面传过来的角色信息判断当前页面的按钮操作
      roleInfo: null,

      // 任务id
      taskId: null,
      // 项目id
      projectId: null,
      // 从后端那获取到的项目负责人id
      staffId: null,
      // 当前登录人的staffId
      loginStaffId: null,
      // 任务是否是由项目负责人确认，0、未确认，1、已确认
      isConfirm: 0,
      // 是否是执业人员0：不是，1：是
      isPractice: null,
      // 是否是项目负责人0：不是，1：是
      isProjectHead: null,

      // 从缓存中获取到的人脸图像
      fileUrls: null,
      times: 10, // 倒计时函数中的时间字段

      placeRange: null, // 从后端获取执业范围
      practiceStates: true, // 用于判断确认按钮和开始执业按钮的展示，正常是展示的，当vuex中的practiceState为look时不展示
      displayBtn: false, // 确认任务喝执业的防抖
      loading: false,

      // 表单列表
      formList: [
        {
          name: '项目信息',
          padding: false,
          children: [
            {
              name: '项目名称',
              value: 'projectName',
              class: 'formItem',
              type: 'span'
            },
            {
              name: '项目地址',
              value: 'projectAddress',
              class: 'formItem',
              type: 'span'
            }
          ]
        },
        {
          name: '任务信息',
          padding: false,
          children: [
            {
              name: '任务名称',
              value: 'name',
              class: 'formItem',
              type: 'span'
            },
            {
              name: '任务开始时间',
              value: 'startDate',
              class: 'formItem',
              type: 'span'
            },
            {
              name: '任务结束时间',
              value: 'endDate',
              class: 'formItem',
              type: 'span'
            }
          ]
        },
        {
          name: '当前定位',
          padding: true,
          children: [
            {
              type: 'map'
            },
          ]
        },
        {
          name: '备注',
          padding: false,
          children: [
            {
              type: 'textarea',
              value: 'remark',
              class: 'formItem formItemTitle',
            },
          ]
        }
      ]
    };
  },
  onLoad(e) {
    new Promise((resolve, reject) => {
      if (this.practiceState == "look") this.practiceStates = false;
      // 获取任务id
      this.taskId = e.taskId;
      this.$store.state.unitTask.taskId = e.taskId;
      // 获取项目id
      this.projectId = e.projectId;
      resolve();
    }).then((res) => {
      this.getForm();
      this.getObtainLongitudeAnd();
    });
  },
  onShow() {
    // 确认任务
    if (this.form.projectLeader != null) {
      this.fileUrls = this.form.projectLeader;
      // 调用人脸比对接口
      this.checkPeople("1");
    }
    // 开始执业
    if (this.form.fileUrls) {
      this.fileUrls = this.form.fileUrls;
      uni.showLoading({
        title: "加载中",
      });
      // 调用人脸比对接口
      this.checkPeople("2");
    }
  },
  mounted() {
    this.meanwhile();
  },
  methods: {
    ...mapMutations(['manage', 'SAVEALLTIMEDATE']),
    ...mapMutations(['unitTask', 'save_examine']),
    showLook(key) {
      let that = this;
      let data = that.practiceState.indexOf(key) != "-1";
      return data;
    },
    navToLook() {
      this.navToForm(1);
      this.displayBtn = false;
    },
    // 解析map地图组件
    meanwhile() {
      let that = this;
      uni.getLocation({
        type: "wgs84",
        altitude: true,
        isHighAccuracy: true,
        success(res) {
          that.centerPoint.latitude = res.latitude;
          that.centerPoint.longitude = res.longitude;
          that.scale = 14;
          // 创建一个标记
          let datas = {
            id: 0,
            latitude: res.latitude, //纬度
            longitude: res.longitude, //经度
            width: 20,
            height: 20,
            alpha: 1, //透明度
            iconPath: '/static/position.png'
          };
          that.$set(that.markers, 0, datas);
        },
      });
    },
    // 进入页面时，就获取当前执业人员是否为中级及中级以上人员
    getJudgmentLevel() {
      this.$store.dispatch("judgmentLevel", this.loginStaffId).then((dist) => {
        this.$store.commit("savefUserName", dist.data.name || null);
        this.$store.commit("savefUserIdCard", dist.data.idCard || null);
      });
    },
    // 获取表单信息
    getForm() {
      if (this.loading) return;

      this.loading = true;
      uni.showLoading({
        title: "正在加载请稍后",
        mask: true,
      });
      let that = this;
      return new Promise((resolve, reject) => {
        this.$store
          .dispatch("unitForm", this.taskId)
          .then((res) => {
            if (res && res.code === 200) {
              this.valiFormData = res.data;
              //! 将该项目的计划开始时间和计划结束时间缓存起来，用于上传时比较是否允许上传
              let saveDate = {
                startDate: res.data.startDate,
                endDate: res.data.endDate,
                lastTime: res.data.lastExecuteTime,
              }
              that.SAVEALLTIMEDATE(saveDate);
              // let dist = that.addDate(res.data.lastExecuteTime, 7)
              // if (res.data.lastExecuteTime && (new Date(dist) < new Date())) {
              //   this.displayBox = false;
              // }
              resolve(res.data);
            } else {
              this.displayBox = true;
            }
          })
          .finally(() => {
            let timer = setTimeout(() => {
              this.loading = false;
              uni.hideLoading();
              clearTimeout(timer);
            }, 3000);
          });
      });
    },
    addDate(date, days) {
      var d = new Date(date);
      d.setDate(d.getDate() + days);
      var m = d.getMonth() + 1;
      return d.getFullYear() + "-" + m + "-" + d.getDate();
    },

    // 获取项目负责人id和经纬度信息
    getObtainLongitudeAnd() {
      let dist = {
        taskId: this.taskId,
      };
      let that = this;
      return new Promise((resolve, reject) => {
        this.$store.dispatch("ObtainLongitudeAndLatitude", dist).then((res) => {
          if (res && res.code === 200) {
            new Promise((resolve, reject) => {
              this.lonLat = res.data.lonLat;
              // 将获取到的项目负责人id暂存
              this.staffId = res.data.projectHead;
              // 将获取到的登录人id暂存
              this.loginStaffId = res.data.loginStaffId;
              this.$store.commit("save_staffId", res.data.loginStaffId);

              //  获取该项目是否已经确认过任务(1是0否)否则展示确认任务按钮
              this.isConfirm = res.data.isConfirm;
              // 获取该项目的执业人员是否为本账户所属(1是0否)是则可以执业任务
              this.isPractice = res.data.isPractice;
              // 获取该项目的项目负责人员是否为本账户所属(1是0否)是则可以确认任务
              this.isProjectHead = res.data.isProjectHead;

              // 获取该项目的执业范围
              this.placeRange = res.data.placeRange;
              if (this.loginStaffId) this.getJudgmentLevel();
              // 判断是否有经纬度，如果没有，则不校验当前位置，有则校验
              if (that.lonLat != null) {
                let demoIp = that.lonLat.split(",");
                resolve(demoIp);
              }
            }).then((res) => {
              // 创建圆内的数据信息，并赋值给this.circles
              let data = {
                latitude: res[0], //纬度
                longitude: res[1], //经度
                radius: this.placeRange / 2,
                strokeWidth: 1,
                fillColor: "#3491b344",
                color: "#3491b3",
              };

              that.$set(that.circles, 0, data);
            });
            resolve(res.data);
          } else {
            this.displayBox = true;
          }
        });
      });
    },
    addDate(date, days) {
      var d = new Date(date);
      d.setDate(d.getDate() + days);
      var m = d.getMonth() + 1;
      return d.getFullYear() + '-' + m + '-' + d.getDate();
    },
    // 确认执业调用的函数
    async navTo() {
      let that = this;
      // 判断获取详情接口是否异常，如果异常则无法点击确认执业按钮
      if (this.displayBox) return;
      // 当displayBtn为true时代表已经有一个动作了
      if (this.displayBtn) return;
      this.displayBtn = true
      // let res = that.$store.state.manage.lastTime
      // let dist = that.addDate(res, 7)
      // if (dist) {
      //   if (new Date(dist) < new Date()) {
      //     uni.showModal({
      //       title: '警告',
      //       content: '已超出执业完成时间7天，无法确认任务',
      //     });
      //     this.displayBtn = false
      //     return
      //   }
      // }
      await that.verifyTask('projectLeader', 1)
    },
    // 开始执业调用的函数
    async sureTo() {
      let that = this;
      // 判断获取详情接口是否异常，如果异常则无法点击确认执业按钮
      if (this.displayBox) return;
      // 当displayBtn为true时代表已经有一个动作了
      if (this.displayBtn) return;

      this.displayBtn = true
      if (this.practiceState != 'look') {
        await that.verifyTask('fileUrls', 2)
      } else {
        this.navToForm(2);
        this.displayBtn = false
      }
    },
    // 人脸比对
    checkPeople(key) {
      let that = this
      // 人脸识别所需参数(固定写法)
      let data = {
        filePath: this.fileUrls,
        staffId: this.loginStaffId, //! 必须传执业者登录的id
      };
      new Promise((resolve, reject) => {
        this.$store
          .dispatch("checkFace", data)
          .then((res) => {
            uni.hideLoading();
            let keys = key == 1 ? 'projectLeader' : 'fileUrls'
            this.save_examine({ key: keys, value: null })
            if (res && res.code === 200) {
              // 识别成功
              if (res.data == 1) {
                resolve()
              } else if (res.data == 3) {
                this.$showToast({
                  show: true,
                  text: "识别人脸失败",
                });
                // 清空图片
                // this.$store.state.unitTask.fileUrls = null;
                this.save_examine({ key: 'fileUrls', value: null })
                this.$store.commit("save_url", null);
                reject()
              } else if (res.data == 4) {
                // 弹出错误信息
                this.$showToast({
                  show: true,
                  text: '活体检测失败'
                })
                // this.$store.state.unitTask.fileUrls = null;
                this.save_examine({ key: 'fileUrls', value: null })
                this.$store.commit("save_url", null);
                reject()
              } else if (res.data == 0) {
                // 弹出错误信息
                this.$showToast({
                  show: true,
                  text: '识别人脸失败'
                })
                // this.$store.state.unitTask.fileUrls = null;
                this.save_examine({ key: 'fileUrls', value: null })
                this.$store.commit("save_url", null);
                reject()
              }
            } else {
              this.$showToast({
                show: true,
                text: `识别人脸失败,状态码为${res.code}`,
              });
              // this.$store.state.unitTask.fileUrls = null;
              this.save_examine({ key: 'fileUrls', value: null })
              // 清空图片
              this.$store.commit("save_url", null);
              reject()
            }
          })
          .finally(() => {
            // 清空图片
            // this.$store.state.unitTask.fileUrls = null;
            // this.$store.commit("save_url", null);
          });
      }).then(() => {
        let newFileUrl = that.fileUrls.split(',')[5]
        uni.downloadFile({
          url: that.baseApiUrl + newFileUrl,
          success: ({ statusCode, tempFilePath }) => {
            if (statusCode === 200) {
              uni.uploadFile({
                url: that.baseApiUrl + '/common/uploadStaffFile',
                name: 'file',
                header: {
                  Authorization: that.$store.state.login.userInfo.token,
                },
                filePath: tempFilePath,
                success: uploadFileRes => {
                  // 清空图片
                  // that.$store.state.unitTask.fileUrls = null;
                  that.save_examine({ key: 'fileUrls', value: null })
                  that.$store.commit("save_url", null);
                  let image = that.baseApiUrl + JSON.parse(uploadFileRes.data).fileName
                  // uni.getLocation({
                  //   type: "gcj02",
                  //   success: function (res) {
                  //     let longitudeAndLatitude = res.latitude + "," + res.longitude || null;
                  //     let data = {
                  //       projectId: that.projectId,
                  //       staffId: that.loginStaffId,
                  //       taskId: that.taskId,
                  //       executeCoordinate: longitudeAndLatitude,
                  //       staffFace: image,
                  //     }
                  //     that.$store.dispatch('taskExcuteRecordList', data).then(res => {
                  //       uni.hideLoading();
                        that.navToForm(key);
                  //     })
                  //   },
                  // });
                },
                fail: err => {
                  uni.showToast({
                    title: err,
                    icon: 'none',
                    duration: 2000
                  });
                }
              });
            }
          }
        })
      })

    },
    // 跳转至采集页面
    navToForm(key) {
      // 该字段代表是开始执业还是确认任务(key=1时代表确认任务confirm；2时代表开始执业practice)
      let design = key == '1' ? 'confirm' : 'practice'
      if (this.practiceState == 'look') design = 'confirm'
      // isConfirm代表是否已经确认过这个任务了
      let isConfirm = key == '1' ? this.isConfirm : '1'
      uni.navigateTo({
        url:
          "../../pages_workTableChild/manage/CategoryGrade?staffId=" +
          this.staffId +
          "&isConfirm=" +
          isConfirm +
          "&loginStaffId=" + this.loginStaffId +
          "&design=" + design
      });
    },
    btnClick() {
      uni.navigateTo({
        url: "/pages_workTableChild/manage/Offline?taskId=" + this.taskId
      })
    },

    /**
     * @description: 开始执业及确认任务的校验操作
     * 逻辑顺序
     * 1、通过uni.getLocation函数获取当前经纬度信息，返回值即为经纬度，将其进行拼接，resolve给下一步
     * 2、获取到拼接好后的经纬度信息后，调用接口uploadObtain将origins(当前经纬度)和destination(执业地址的经纬度)传给后端做对比
     *   2.1、对比结果在1公里以内时,方可进行下一步操作
     *   2.2、对比结果在1公里以外时,无法进行下一步操作
     * 3、当对比结果在1公里以内时，前往执业页面
     */
    verifyTask(key, num) {
      let that = this;
      // 新增一个字段用于存储倒计时函数
      var setTimes;
      uni.showLoading({
        title: '加载中'
      });
      return new Promise((resolve, reject) => {
        // uni.getLocation({
        //   type: "gcj02",
        //   success: function (res) {
        //     let longitudeAndLatitude = res.latitude + "," + res.longitude || false;
        //     resolve(longitudeAndLatitude);
        //   },
        //   fail: function (err) {
        //     if (that.times <= 0) {
        //       clearInterval(setTimes);
        //       that.times = 10;
        //     }
        //     uni.showToast({
        //       title: `${that.times}秒后重新定位`,
        //       icon: "error",
        //     });
        //     reject('获取定位失败')
        //   },
        // });
        resolve(true);
        // reject('获取定位失败')
      }).then(res => {
        // 判断是否有经纬度，如果没有，则不校验当前位置，有则校验
        var demo = true;
        // if (that.lonLat != null) {
        //   let demoIp = that.lonLat.split(",");
        //   let ipDist = demoIp[0] + "," + demoIp[1].trim();
        //   setTimes = setInterval(() => {
        //     that.times--;
        //   }, 1000);
        //   // 返回值为拼接后的经纬度
        //   let dist = {
        //     origins: res,
        //     destination: ipDist,
        //     placeRange: that.placeRange / 2
        //   };
        //   demo = that.$store.dispatch("uploadObtain", dist).then((list) => {
        //     return JSON.parse(list.data.result);
        //   });
        // }
        return demo;
      }).then((res) => {
        if (res) {
          // ! 跳转至人脸识别
          uni.navigateTo({
            url: `../../pages_workTableChild/manage/recognition?label=${key}`,
          });
          //! 跳过人脸识别
          // this.navToForm(num);
        } else {
          uni.showToast({
            title: `工作人员未在工作场所范围内！`,
            icon: "none",
          });
        }
      }).catch(() => {
        return false
      }).finally(() => {
        this.displayBtn = false
        uni.hideLoading();
      })
    }
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

::v-deep .uni-section {
  background-color: transparent;
  margin-top: 0
}

::v-deep uni-map {
  width: 100%;
  height: 400rpx;
}

.info_box {
  min-height: 100vh;

  .card {
    min-height: calc(100% - 80rpx);
    background: $OVERALL_SITUATION_BACKGROUND_GRADIENT;

    .formItem {
      display: flex;
      align-items: center;
      padding-bottom: 25rpx;
      width: calc(100% - 40rpx);
      margin: 0 auto 24rpx;
      background-color: #fff;
      border-radius: 20rpx;
      min-height: 110rpx;
      padding: 0 24rpx;

      .label {
        color: #333;
        font-size: 28rpx;
        font-weight: 400;
        line-height: 36rpx;
        width: 40%;
      }

      .required {
        &::before {
          content: "*";
          margin: 0 10rpx;
          color: #ea0707;
        }
      }

      .content {
        text-align: right;
        width: 60%;
        font-size: 28rpx
      }
    }

    .formItemTitle {
      flex-direction: column !important;
      align-items: flex-start !important;
      padding: 24rpx !important;

      .content {
        text-align: left !important;
        width: 100% !important;
      }
    }

    .map {
      width: 100%;
      height: 400rpx;
    }
  }




  &-btn {
    width: 100%;
    height: 100rpx;
    background-color: #ffffff;
    position: fixed;
    bottom: 0;
    border-top: 1rpx solid #e5e5e5;

    &-sure {
      width: 700rpx;
      height: 88rpx;
      line-height: 88rpx;
      background: $OVERALL_CONFIRM_BUTTON_COLOR;
      color: #ffffff;
      text-align: center;
      font-size: 30rpx;
      font-family: Source Han Sans CN;
      font-weight: 400;
      margin: 20rpx auto 0;
      border-radius: 10rpx;
    }

    &-combination {
      width: 750rpx;
      display: flex;
      flex-direction: row;
      margin: 10rpx auto;
      justify-content: space-around;

      &-btn {
        flex: 1;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        background: $OVERALL_CONFIRM_BUTTON_COLOR;
        color: #ffffff;
        font-size: 28rpx;
        font-family: Source Han Sans CN;
        font-weight: 400;
        border-radius: 10rpx;
        margin: 0 20rpx;
      }

      .sureBtns {
        background: #D9EBFF;
        font-size: 30rpx;
        color: #0090FE;
      }
    }
  }

  &-btn2 {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: 30rpx;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #ffffff;
    margin-bottom: 50rpx;
    display: flex;

    &-btnbox {
      margin: 0 20rpx;
      background: #335ac7;
      border-radius: 30rpx;
      flex: 1;
    }
  }
}

/deep/.uni-section {
  margin-top: 0;
  margin-bottom: 20rpx;
  border-radius: 20rpx;
}
</style>
